#!/bin/bash

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[信息]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[成功]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[警告]${NC} $1"
}

print_error() {
    echo -e "${RED}[错误]${NC} $1"
}

# 检查端口是否被占用
check_port() {
    local port=$1
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        return 0  # 端口被占用
    else
        return 1  # 端口空闲
    fi
}

# 停止服务函数
stop_service() {
    local name=$1
    local port=$2
    local pid_file="logs/${name,,}.pid"
    
    print_info "停止 $name (端口: $port)..."
    
    # 尝试从PID文件停止
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if kill -0 "$pid" 2>/dev/null; then
            kill -TERM "$pid" 2>/dev/null
            sleep 2
            if kill -0 "$pid" 2>/dev/null; then
                kill -KILL "$pid" 2>/dev/null
            fi
            rm -f "$pid_file"
            print_success "$name 已停止 (PID: $pid)"
        else
            rm -f "$pid_file"
        fi
    fi
    
    # 通过端口停止进程
    if check_port $port; then
        local pids=$(lsof -Pi :$port -sTCP:LISTEN -t)
        for pid in $pids; do
            kill -TERM "$pid" 2>/dev/null
            sleep 1
            if kill -0 "$pid" 2>/dev/null; then
                kill -KILL "$pid" 2>/dev/null
            fi
            print_success "$name 进程已停止 (PID: $pid)"
        done
    fi
}

echo
echo "==============================================================================="
echo "                        MCP代码生成系统 v2.0"
echo "                         服务停止脚本 (Linux)"
echo "==============================================================================="
echo

print_info "正在停止所有服务..."
echo

# 定义服务列表
services=(
    "MCP_Generator:8010"
    "Generated_MCP_Server:8000"
    "MCP_Server_Manager:8011"
    "Agent_Client:8080"
    "Web_Frontend:8090"
)

# 停止各个服务
for service in "${services[@]}"; do
    IFS=':' read -r name port <<< "$service"
    stop_service "$name" "$port"
done

# 清理相关进程
print_info "清理相关进程..."
pkill -f "uvicorn.*mcp" 2>/dev/null
pkill -f "python.*mcp" 2>/dev/null
pkill -f "web_server.py" 2>/dev/null
pkill -f "agent_client" 2>/dev/null
pkill -f "qwen_agent" 2>/dev/null

# 强制清理顽固进程
print_info "强制清理顽固进程..."
pkill -9 -f "uvicorn.*mcp" 2>/dev/null
pkill -9 -f "python.*mcp" 2>/dev/null

# 清理可能的僵尸进程
print_info "清理僵尸进程..."
ps aux | grep -E "(mcp|agent_client|web_server)" | grep -v grep | awk '{print $2}' | xargs -r kill -9 2>/dev/null

# 等待进程完全停止
sleep 3

# 验证服务是否已停止
echo
print_info "验证服务停止状态..."
running_services=()
for service in "${services[@]}"; do
    IFS=':' read -r name port <<< "$service"
    if check_port $port; then
        print_warning "$name 仍在运行 (端口: $port)"
        running_services+=("$name")
    else
        print_success "$name 已停止 (端口: $port)"
    fi
done

echo
if [ ${#running_services[@]} -eq 0 ]; then
    print_success "所有服务已成功停止！"
else
    print_warning "以下服务仍在运行: ${running_services[*]}"
    print_info "请手动检查或使用 sudo 权限停止"
fi

# 清理临时文件和缓存
echo
print_info "清理临时文件和缓存..."
rm -f logs/*.pid 2>/dev/null
# 清理可能的缓存文件
find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null
find . -type f -name "*.pyc" -delete 2>/dev/null
print_success "临时文件已清理"

echo
print_info "服务日志保存在 logs/ 目录中"
print_info "清理所有日志: rm -f logs/*.log"
print_info "如需完全重置，请运行: ./scripts/reset.sh"
echo
